package com.example.myandroidtest.common.http;

import com.example.myandroidtest.common.base.Config;
import com.example.myandroidtest.common.http.print.PrintGsonConverterFactory;
import com.example.myandroidtest.utils.L;
import com.example.myandroidtest.utils.ToastUtils;

import java.util.concurrent.TimeUnit;


import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by liukun on 16/3/9.
 */
public class HttpUtils {

    // 文本的 mediaType
    public static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/x-www-form" +
            "-urlencoded; charset=utf-8");
    // 文件的 mediaType
    public static final MediaType MEDIA_TYPE_FILE = MediaType.parse("multipart/form-data; " +
            "charset=utf-8");

    public static final String MEDIA_TEXT = "application/x-www-form-urlencoded";// 文本
    public static final String MEDIA_FILE = "multipart/form-data";// 文件


    // 默认超时  10秒
    private static final int DEFAULT_TIMEOUT = 10;

    private static Api api;

    public static Api getApi() {
        return getInstance().api;
    }

    static Retrofit retrofit;

    //构造方法私有
    private HttpUtils() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new ReqeustPrintInterceptor());
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        retrofit =
                new Retrofit.Builder().client(builder.build()).addConverterFactory(PrintGsonConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).baseUrl(Config.getDefaultUrlNetpath()).build();
        L.e("链接的网络地址   " + Config.getDefaultUrlNetpath());
        api = retrofit.create(Api.class);
    }


    /**
     * 清除缓存  切换IP地址
     */
    public static void clearCache(String netPath) {
        Config.setDefaultUrlNetpath(netPath);

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        retrofit =
                new Retrofit.Builder().client(builder.build()).addConverterFactory(PrintGsonConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).baseUrl(Config.getDefaultUrlNetpath()).build();

        api = retrofit.create(Api.class);
    }


    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final HttpUtils INSTANCE = new HttpUtils();
    }

    //获取单例
    public static HttpUtils getInstance() {
        return SingletonHolder.INSTANCE;
    }


    /**
     * @param o
     * @param s
     */
    public static <T> void toSubscribe(Observable<HttpResult<T>> o, Subscriber<T> s) {
        Observable<T> map = o.map(new HttpResultFunc<T>());
        map.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(s);
    }

    /**
     * 原始   toSunscribe
     *
     * @param o
     * @param s
     * @param <T>
     */
    public static <T> void originalToSubscribe(Observable<T> o, Subscriber<T> s) {
//        o.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn
//                (AndroidSchedulers.mainThread()).subscribe(s);

    }


    /**
     * 处理数据
     *
     * @param <T>
     */
    public static class HttpResultFunc<T> implements Function<HttpResult<T>, T> {
        @Override
        public T apply(HttpResult<T> httpResult) {
            if (httpResult.getStatus() != HttpResult.SUCCESS_CODE)
                throw new ApiException(httpResult.getStatus(), httpResult.getMessage());
            return httpResult.getData();
        }
    }


    /**
     * 是否请求成功
     *
     * @param
     * @return
     */
    public static boolean isRequestSuccess(HttpResult<? extends Object> result) {
        if (result.getStatus() == HttpResult.SUCCESS_CODE) {
            return true;
        } else {
            ToastUtils.showShort(result.getMessage());
            return false;
        }
    }


//    // 抽出来  code 1 2
//    public void getTopMovie(Subscriber<TestMolde> subscriber, int start, int count) {
//
//        api.getTopMovie(start, count)
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);
//    }


//   // 原生
//    public void getTopMovie(Subscriber<TestMolde> subscriber, int start, int count) {
//
//        api.getTopMovie(start, count)
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);
//    }


//    /**
//     * 用于获取豆瓣电影Top250的数据
//     * @param subscriber  由调用者传过来的观察者对象
//     * @param start 起始位置
//     * @param count 获取长度
//     */
//    public void getTopMovie(Subscriber<List<Subject>> subscriber, int start, int count){
//
//        Observable observable = movieService.getTopMovie(start, count)
//                .map(new HttpResultFunc<List<Subject>>());
//
//        toSubscribe(observable, subscriber);
//    }
//
//    private <T> void toSubscribe(Observable<T> o, Subscriber<T> s){
//
//         o.subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(s);
//    }
//
//    /**
//     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
//     *
//     *  // 处理msg  和  code
//     * @param <T>   Subscriber真正需要的数据类型，也就是Data部分的数据类型
//     */
//    private class HttpResultFunc<T> implements Func1<HttpResult<T>, T>{
//
//        @Override
//        public T call(HttpResult<T> httpResult) {
//            if (httpResult.getCount() == 0) {
//                    throw new ApiException(100);
//            }
//            return httpResult.getSubjects();
//        }
//    }

}
